﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Card.Common
{
    public class AreaCache
    {
        private static List<Entity.Area> lstArea = null;

        private static List<Entity.Area> m_LstProvince = null;

        private static Dictionary<int, List<Entity.Area>> m_DicChildren = new Dictionary<int, List<Entity.Area>>();

        static AreaCache()
        {
            Refresh();
        }

        public static void Refresh()
        {
            lstArea = BLL.AreaManager.GetAllArea();
            m_DicChildren.Clear();
            m_LstProvince = null;
        }

        public static Entity.Area GetAreaByCode(string siteCode)
        {
            return lstArea.Find(e => string.Compare(e.SiteCode, siteCode) == 0);
        }

        public static Entity.Area GetParentArea(Entity.Area area)
        {
            return lstArea.Find(e => e.ID == area.ParentAreaID);
        }

        public static List<Entity.Area> GetProvinceArea()
        {
            if (m_LstProvince == null)
            {
                m_LstProvince = (lstArea.FindAll(e => string.Compare(e.AreaType, "1") == 0));
                m_LstProvince.Sort(new Comparison<Card.Entity.Area>(delegate(Card.Entity.Area v, Card.Entity.Area v1) { return v.Sort > v1.Sort ? 1 : (v.Sort == v1.Sort ? 0 : -1); }));
            }
            return m_LstProvince;
        }

        public static List<Entity.Area> GetChildrenArea(int parentID)
        {
            if (!m_DicChildren.Keys.Contains(parentID))
            {
                List<Entity.Area> lst = lstArea.FindAll(e => e.ParentAreaID == parentID);
                lst.Sort(new Comparison<Card.Entity.Area>(delegate(Card.Entity.Area v, Card.Entity.Area v1) { return v.Sort > v1.Sort ? 1 : (v.Sort == v1.Sort ? 0 : -1); }));
                m_DicChildren.Add(parentID, lst);                
            }
            return m_DicChildren[parentID];
        }
    }
}
